//封装购物车业务逻辑模块

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from './user'
import { insertCartAPI ,findNewCartListAPI ,delCartAPI} from "@/apis/cart";
export const useCartStore = defineStore('cart' ,()=>{
    const userStore =useUserStore()
    const isLogin =computed(() => userStore.userInfo.token)
    //1.定义state -cartList
    const cartList =ref([])
        //获取最新购物车列表action
        const updataNewList = async() =>{
            const res =await findNewCartListAPI()
            cartList.value=res.result 
        }    
    //2.定义action -addcart
    const addCart = async(goods)=>{
        const { skuId ,count } =goods
        if(isLogin.value){
            //登录之后的购物车逻辑
            insertCartAPI({skuId ,count})
            updataNewList()
        } else {
            //添加购物车操作
        //已添加过 conunt ++
        const item = cartList.value.find((item)=> goods.skuId === item.skuId) //数组查找匹配用法
        if(item){
            //找到了
            item.count += goods.count
        }else{
            //没有添加过直接 Push
            cartList.value.push(goods)
        }
        }
    }
    //删除购物车
    const delCart = async (skuId)=>{
        if(isLogin.value){
            //调用接口实现删除
            await delCartAPI([skuId])
            updataNewList()
        }else{
            const idx =cartList.value.findIndex((item)=> skuId ===item.skuId)
            cartList.value.splice(idx ,1)
        }
    }
    //单选功能
    const singleCheck = (skuId ,selected) =>{
        //通过skuId找到要修改的，然后修改
        const item =cartList.value.find((item) => skuId ===item.skuId)
        item.selected =selected
    }
    //全选功能
    const allCheck = (selected) =>{
        //把cartList中的每一项的selectd都设置为全选框的状态
        cartList.value.forEach((item) =>item.selected =selected)
    }
    //清除购物车
    const clearCart =()=>{
        cartList.value=[]
    }

    //计算属性 
    //1.总的数量
    const allCount = computed(()=>cartList.value.reduce((a,c)=>a + c.count,0))

    //2.总的价钱
    const allPrice = computed(()=>cartList.value.reduce((a,c)=>a + c.count *c.price,0))
    
    //3.是否全选
    const isAll =computed(()=>cartList.value.every((item) =>item.selected))

    //4.已选择数量
    const selectedCount =computed(() =>cartList.value.filter(item =>item.selected).reduce((a,c)=>a + c.count,0))
    //5.已选择总价
    const selectedPrice =computed(() =>cartList.value.filter(item =>item.selected).reduce((a,c)=>a + c.count*c.price,0))


    return{
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updataNewList
    }
},{
    persist:true
})